#include "CorePch.h"
#include "JSystem.h"
#include "JUtility.h"



namespace JJc{

bool LoadFile( __in const wchar* fileName, __out int8*& pBuffer, __out uint32& fileSize )
{
	_stat fileInfo;
	if ( !fileName || _wstat(fileName, &fileInfo) != 0 )
	{
		//file does not exist	
		TRACE( (wstring(fileName) + wstring(L" could not be found.")).c_str());
		pBuffer = 0;
		fileSize = 0;
		return false;
	}

	FILE* pFile =  _wfopen( fileName, L"rb");
	if ( !pFile )
	{
		//open file failed
		TRACE( (wstring(fileName) + wstring(L" could not be opened.")).c_str());
		pBuffer = 0;
		fileSize = 0;
		return false;
	}
	fileSize = fileInfo.st_size;
	pBuffer = (int8*)malloc( fileSize );

	uint64 readCount = fread(pBuffer, sizeof(int8), fileSize, pFile);
	if ( fclose( pFile)!=0  || readCount != fileSize)
	{		
		free(pBuffer);
		pBuffer  = NULL;		
		fileSize = 0;
		return false;
	}
	return true;
}

bool SaveFile( __in const wchar* fileName, __in const int8* pBuffer, __in const uint32 fileSize )
{
	if (!pBuffer || fileSize <= 0)
	{		
		ASSERT(0);
		return false;
	}

	FILE* pFile = _wfopen(fileName, L"wb");
	if (!pFile)
	{
		return false;
	}

	uint64 writeBytes = fwrite(pBuffer, sizeof(int8), fileSize, pFile);
	if ( fclose( pFile)!=0  || writeBytes != fileSize)
	{
		ASSERT( 0 );
		return false;
	}

	return true;

}

wstring String2WString( __in const char* pszSrc, __in const size_t nLen )
{
	size_t nSize = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pszSrc, nLen, 0, 0);
	if(nSize <= 0) 
	{
		return NULL;
	}
	wchar *pwszDst = new wchar[nSize+1];
	if( NULL == pwszDst) 
	{
		return NULL;
	}
	MultiByteToWideChar(CP_ACP, 0,(LPCSTR)pszSrc, nLen, pwszDst, nSize);
	pwszDst[nSize] = 0;
	if( pwszDst[0] == 0xFEFF) // skip Oxfeff
	{
		for(uint i = 0; i < nSize; ++i) 
		{
			pwszDst[i] = pwszDst[i+1]; 
		}
	}
	std::wstring destString(pwszDst);
	delete pwszDst;
	return destString;	
}

string WString2String( __in const wchar* pwszSrc )
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
	if (nLen<= 0) 
	{
		return std::string("");
	}
	char* pszDst = new char[nLen];
	if (NULL == pszDst) 
	{
		return std::string("");
	}
	WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
	pszDst[nLen -1] = 0;
	string strTemp(pszDst);
	delete [] pszDst;
	
	return strTemp;
}

wstring Number2WString( const int32& i )
{
	wchar temp [24];
	_snwprintf_s(temp, 24, _TRUNCATE, L"%d", i);	
	return temp;
	
}

JJc::wstring Number2WString( const uint32& i )
{
	wchar temp[24];
	_snwprintf_s(temp, 24, _TRUNCATE, L"%u", i);
	return temp;

}

JJc::wstring Number2WString( __in const double& i )
{
	wchar temp[64];
	_snwprintf_s(temp,64, _TRUNCATE,L"%f",i);
	return temp;
}
} //end namespace
